package com.goblin.security;

import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.goblin.common.response.Code;
import com.goblin.common.response.Message;
import com.goblin.common.response.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ParamLogFilter implements Filter {

	private static final Logger logger = LoggerFactory.getLogger(ParamLogFilter.class);

	public ParamLogFilter() {
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

	}

	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
			FilterChain filterChain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		OutputStream outputStream = response.getOutputStream();

		String url = request.getRequestURI();

		try {

			servletRequest.getRequestDispatcher(url).forward(request, response);
		}
		catch (Exception ex) {
			ex.printStackTrace();
			String resp = JSONObject.toJSON(Response
					.failure(Code.SERVICE_UNAVAILABLE, Message.SERVER_INTERNAL_ERROR))
					.toString();
			outputStream.write(resp.getBytes());
		}
	}

	@Override
	public void destroy() {

	}

	public String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}
}